/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: Displays a login form and handles input. Also manages a list of saved users.
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.ArrayList;

import com.google.analytics.tracking.android.EasyTracker;

import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;
import us.in.lib.acpl.Mobile_ACPL.util.JSONArrayPrefs;
import us.in.lib.acpl.Mobile_ACPL.ws.LoginHandler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

	private LoginActivity thisActivity = this;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		setupSavedUsers();
		EditText et = (EditText) findViewById(R.id.pinBox);
		et.setRawInputType(Configuration.KEYBOARD_QWERTY);
		findViewById(R.id.loginButton).setOnClickListener(this);
		findViewById(R.id.loginCancelButton).setOnClickListener(this);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

	}
	  @Override
	  public void onStart() {
	    super.onStart();
	    EasyTracker.getInstance().activityStart(this); // Add this method.
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	    EasyTracker.getInstance().activityStop(this); // Add this method.
	  }
	public void setupSavedUsers() {
		ArrayList<String> users = JSONArrayPrefs.getStringArrayPref(this,
				"savedUsers");

		// show button
		this.findViewById(R.id.savedUsersButton).setOnClickListener(
				new SavedUserListener());

	}

	@Override
	public void onClick(View view) {
		TextView t = (TextView) view;

		if (t.getText().toString().equals("Cancel")) {
			finish();
		} else {
			login();
		}

	}

	public void login() {

		// Get user input from the login screen.
		EditText t = (EditText) findViewById(R.id.libraryCardBox);
		String user = t.getText().toString();
		t = (EditText) findViewById(R.id.pinBox);
		String pin = t.getText().toString();
		t = (EditText) findViewById(R.id.nicknameBox);
		String nickname = t.getText().toString();
		CheckBox c = (CheckBox) findViewById(R.id.pinRemember);
		String remember = String.valueOf(c.isChecked());
		// Check for sane input
		if (user == null || user.equalsIgnoreCase("") || pin == null
				|| pin.equalsIgnoreCase("") || !user.startsWith("2")
				|| user.length() != 14) {

			Toast toast = Toast.makeText(this,
					"Please enter a valid library card number and PIN.",
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} else {
			// If the box was checked, set values in the preferences file.
			c = (CheckBox) findViewById(R.id.remember);
			if (c.isChecked()) {
				ArrayList<String> users = JSONArrayPrefs.getStringArrayPref(
						this, "savedUsers");
				ArrayList<String> pins = JSONArrayPrefs.getStringArrayPref(
						this, "savedPins");
				ArrayList<String> nicknames = JSONArrayPrefs
						.getStringArrayPref(this, "savedNicknames");
				ArrayList<String> remembers = JSONArrayPrefs
						.getStringArrayPref(this, "savedRemembers");
				users.add(user);
				pins.add(pin);
				nicknames.add(nickname);
				remembers.add(remember);
				JSONArrayPrefs.setStringArrayPref(this, "savedUsers", users);
				JSONArrayPrefs.setStringArrayPref(this, "savedPins", pins);
				JSONArrayPrefs.setStringArrayPref(this, "savedNicknames",
						nicknames);
				JSONArrayPrefs.setStringArrayPref(this, "savedRemembers",
						remembers);
			}

			SharedPreferences prefs = getSharedPreferences("myPrefs",
					Context.MODE_WORLD_WRITEABLE);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString("user", user);
			editor.putString("pin", pin);
			editor.putString("nickname", nickname);
			editor.commit();
			String[] arr = { user, pin };
			Activity act = this;
			LoginHandler handler = new LoginHandler();
			handler.handleLoginButtonPress(act, arr, act.getIntent()
					.getStringExtra("destination"), c.isChecked());

		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {

			SharedPreferences prefs = getSharedPreferences("myPrefs",
					Context.MODE_WORLD_WRITEABLE);
			SharedPreferences.Editor editor = prefs.edit();

			editor.putString("user", data.getStringExtra("user"));
			editor.putString("pin", data.getStringExtra("pin"));
			editor.putString("nickname", data.getStringExtra("nickname"));
			editor.commit();
			String[] arr = { data.getStringExtra("user"),
					data.getStringExtra("pin") };
		
			LoginHandler handler = new LoginHandler();
			handler.handleLoginButtonPress(this, arr, this.getIntent()
					.getStringExtra("destination"), false);
		}

	}

	@Override
	public void onResume() {
		super.onResume();

		SharedPreferences prefs = this.getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE);
		if (prefs.getBoolean("loggedIn", false)) {
			Intent intent = new Intent(this, Mobile_ACPLActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		

	}

	private class SavedUserListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(thisActivity, SavedUserActivity.class);
			thisActivity.startActivityForResult(intent, 0);
		}

	}
	

}
